package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.dao.SpitDao2;
import com.tensquare.spit.pojo.Spit2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SpitService2 {

    @Autowired
    private SpitDao2 spitDao2;

    @Autowired
    private IdWorker idWorker;

    //方式二，加入mongo模板
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询所有
    public List<Spit2> findAll(){
        return  spitDao2.findAll();
    }
    //查询一条
    public Spit2 findById(String id){
        return spitDao2.findById(id).get();
    }

    //新增
    public void save(Spit2 spit2){
        spit2.set_id(idWorker.nextId()+"");
        spit2.setPublishtime(new Date());
        spit2.setVisits(0);//浏览量
        spit2.setShare(0);//分享数
        spit2.setThumbup(0);//点赞数
        spit2.setComment(0);//回复数
        spit2.setState("1");//状态
        //如果当前添加的吐槽，有父节点，那么父节点吐槽回复数要加一
        if(null!=spit2.getParentid() && !"".equals(spit2.getParentid())){
            Query query = new Query();
            //根据父级id查询父级数据
            // Criteria.where("_id").is(spit.getParentid())
            query.addCriteria(Criteria.where("_id").is(spit2.getParentid()));
            Update update = new Update();
            //父节点字段增长1
            update.inc("comment",1);
            mongoTemplate.updateFirst(query,update,"spit2");
        }
        spitDao2.save(spit2);
    }

    //通过父ID查找数据 带分页
    public Page<Spit2> findByParentid(String parentid,int page,int size){
        Pageable pageable = PageRequest.of(page-1,size);
        return  spitDao2.findByParentid(parentid,pageable);
    }
}
